package injection;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * 实现 XxxAware 接口回调
 * @author jackcfan
 * @date 2021/9/16
 */
public class XxxAwareInterfaceInjectionTest implements BeanFactoryAware, BeanNameAware, ApplicationContextAware {
    static BeanFactory beanFactory;
    static ApplicationContext applicationContext;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationContext = new AnnotationConfigApplicationContext();
        // 注册 Configuration class 配置类
        annotationContext.register(XxxAwareInterfaceInjectionTest.class);

        // 启动 Spring 上下文
        annotationContext.refresh();

        XxxAwareInterfaceInjectionTest annotation = annotationContext.getBean(XxxAwareInterfaceInjectionTest.class);

        // annotationContext.getBeanFactory() 代理了 beanFactory
        System.out.println("beanFactory != applicationContext ? "+ (beanFactory != applicationContext));
        System.out.println("annotationContext == applicationContext ? "+ (annotationContext == applicationContext));
        System.out.println("annotationContext.getBeanFactory() == beanFactory ? "+ (annotationContext.getBeanFactory() == beanFactory));

        annotationContext.close();
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("beanFactory>"+beanFactory);
        this.beanFactory = beanFactory;
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("beanname>"+ name);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("applicationContext>"+applicationContext);
        this.applicationContext = applicationContext;
    }
}
